import asyncio
import json
import random
import time

from fastapi import WebSocket, APIRouter


line_router = APIRouter()



def generate_kline_data():
    """生成 K 线数据的函数"""
    close = round(random.uniform(100, 200), 2)
    high = round(random.uniform(100, 200), 2)
    low = round(random.uniform(100, 200), 2)
    open_price = round(random.uniform(100, 200), 2)
    timestamp = int(time.time() * 1000)
    volume = random.randint(100, 1000)
    return {
        "close": close,
        "high": high,
        "low": low,
        "open": open_price,
        "timestamp": timestamp,
        "volume": volume
    }


@line_router.websocket("/line-data")
async def kline_data_websocket(websocket: WebSocket):
        await websocket.accept()
        print("sldkjflskadlfjkasldfj")
        while True:
            # 模拟根据当前时间生成最新的 K 线数据
            kline_data = generate_kline_data()
            print(f"Generated K-line data: {kline_data}")
            # 将数据发送给客户端
            await websocket.send_text(json.dumps(kline_data))
            # 等待一段时间后再发送新数据，模拟实时更新
            await asyncio.sleep(1)
            print('ksjdlkfkajkldf')
